package com.sinoglobal.ningxia.activity.amusement;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.orhanobut.logger.Logger;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.IBase;
import com.sinoglobal.ningxia.activity.amusement.AmusementDialog.AmusementDialogClickListener;
import com.sinoglobal.ningxia.beans.AreaListVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.fragment.AmusementInfoFragment;
import com.sinoglobal.ningxia.frame.AbstractActivity;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.LoctionUtil;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.StringUtil;
import com.sinoglobal.ningxia.widget.ScreenListView;

/**
 * @Title: AmusementActivity.java
 * @Package com.sinoglobal.ningxia.activity.amusement
 * @Description: (娱乐主Activity)
 * @author czz
 * @date 2014-6-19 下午3:13:28
 */
public class AmusementActivity extends AbstractActivity implements IBase, OnCheckedChangeListener, OnClickListener {
	private CheckBox amusementCheckboxArea;// 按区域
	private CheckBox amusementCheckboxClassify;// 按分类
	private CheckBox amusementButtonDistance;// 按距离
	private CheckBox amusementButtonHot;// 按热度
	private Button amusementButtonMapModel;// 地图模式
	private PopupWindow pop1; // 按区域的popupwindow
	private PopupWindow pop2; // 按分类的popupwindow
	private LocationClient mLocationClient; // 定位的客户端
	private String message = "请打开GPS定位,系统能更精准的计算你与商家的距离哦~";
	private int info_num = 1; // 定位成功之后， 发送handler 的 what
	private int popwidth; // 宽
	private int popheight;// 高
	private ScreenListView screenlistview; // 区域View
	private ScreenListView screenlistview1; // 分类View
	public static String type = "type"; // 食府 还是 娱乐
	private LinearLayout amusementLinearlayout; // 主页面布局
	private LinearLayout searchLinearlayout; // 搜索页面布局
	private EditText searchDialogEt;
	private AmusementDialog dialog;// 定位提示对话框
	private boolean flag = false;
	private boolean flag_isfirst = true;
	private TextView searchDialogBtn; // 搜索按钮
	private ProgressDialog locationPd; // 定位的dialog
	private AsyncTask<Void, Void, AreaListVo> asynctask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getContentResolver().registerContentObserver(Settings.Secure.getUriFor(Settings.System.LOCATION_PROVIDERS_ALLOWED), false,
				mGpsMonitor);
		Logger.e("娱乐和美食的主界面");
		FilterRequirement.TYPE = getIntent().getStringExtra(type);
		if (FilterRequirement.ENTERTAINMENT.equals(FilterRequirement.TYPE)) {
			titleView.setText(getString(R.string.entertainment));
			if (FlyApplication.isInActivityFlag == 1) {
				FlyApplication.isGpsFlag = false;
			} else {
				FlyApplication.isGpsFlag = true;
			}
		} else {
			titleView.setText(getString(R.string.cate));
			if (FlyApplication.isInActivityFlag1 == 2) {
				FlyApplication.isGpsFlag = false;
			} else {
				FlyApplication.isGpsFlag = true;
			}
		}
		locationPd = new ProgressDialog(this);
		locationPd.setMessage(getString(R.string.geting_location));
		setContentView(LayoutInflater.from(AmusementActivity.this).inflate(R.layout.activity_amusement, null));
		init();
		showListener();
		beginTransaction = getSupportFragmentManager().beginTransaction();
		// 初始化数据
		// 1、判断用户是否打开gps
		if (LoctionUtil.isOPen(this)) {
			// 去定位
			showLocaltion(true);
		} else {
			if (FlyApplication.isGpsFlag) {
				dialog = new AmusementDialog(this, message, false);
				dialog.alertIvExpression.setVisibility(View.INVISIBLE);
				dialog.setAtdialogclick(new AmusementDialogClickListener() {
					@Override
					public void doConfirm() {
						try {
							Intent intent = new Intent();
							flag = true;
							intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivity(intent);
							dialog.cancel();
						} catch (Exception e) {
							showShortToastMessage(getString(R.string.gps_disabled));
						}
					}

					@Override
					public void doCancel() {
						if (FilterRequirement.ENTERTAINMENT.equals(FilterRequirement.TYPE)) {
							FlyApplication.isInActivityFlag = 1;
						} else {
							FlyApplication.isInActivityFlag1 = 2;
						}
						showLocaltion(false);
						dialog.cancel();
					}
				});
				dialog.show();
			} else {
				showLocaltion(false);
			}
		}
	}

	@Override
	protected void onStop() {
		// Auto-generated method stub
		if (mLocationClient != null) {
			mLocationClient.stop();
		}
		super.onStop();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		if (flag) {
			if (!LoctionUtil.isOPen(this)) {
				showShortToastMessage(getString(R.string.gps_notOpen));
				showLocaltion(false);
			}
			flag = false;
		}
	}

	private void showLocaltion(boolean gpsIsOpen) {
		flag_isfirst = false;
		// 显示获取定位的进度条
		locationPd.show();
		mLocationClient = new LocationClient(AmusementActivity.this); // 声明LocationClient类
		MyLocationListener myListener = new MyLocationListener();
		mLocationClient.registerLocationListener(myListener); // 注册监听函数
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 设置定位模式
		option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);// 返回的定位结果包含地址信息
		option.setNeedDeviceDirect(true);// 返回的定位结果包含手机机头的方向
		option.setOpenGps(gpsIsOpen);
		mLocationClient.setLocOption(option);
		mLocationClient.start();
	}

	@Override
	public void init() {
		/*mLocationManager = (LocationManager)
		 getSystemService(LOCATION_SERVICE);*/
		amusementCheckboxArea = (CheckBox) findViewById(R.id.amusement_checkbox_area);
		amusementCheckboxClassify = (CheckBox) findViewById(R.id.amusement_checkbox_classify);
		amusementButtonDistance = (CheckBox) findViewById(R.id.amusement_button_distance);
		amusementButtonHot = (CheckBox) findViewById(R.id.amusement_button_hot);
		amusementButtonMapModel = (Button) findViewById(R.id.amusement_button_mapmodel);
		templateButtonRight.setBackgroundResource(R.drawable.title_search);
		templateButtonRight.setVisibility(View.VISIBLE);
		popwidth = FlyApplication.widthPixels / 5 * 3;
		popheight = FlyApplication.heightPixels / 2;
		amusementLinearlayout = (LinearLayout) findViewById(R.id.amusement_linearlayout);
		searchLinearlayout = (LinearLayout) findViewById(R.id.search_linearlayout);
		searchDialogBtn = (TextView) findViewById(R.id.search_dialog_btn);
		searchDialogEt = (EditText) findViewById(R.id.search_dialog_et);
	}

	@Override
	public void showListener() {
		amusementCheckboxArea.setOnCheckedChangeListener(this);
		amusementCheckboxClassify.setOnCheckedChangeListener(this);
		amusementButtonDistance.setOnCheckedChangeListener(this);
		amusementButtonHot.setOnCheckedChangeListener(this);
		amusementButtonMapModel.setOnClickListener(this);
		templateButtonRight.setOnClickListener(this);
		searchDialogBtn.setOnClickListener(this);
		templateButtonLeft.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (searchLinearlayout != null) {
					if (searchLinearlayout.getVisibility() == View.VISIBLE) {
						goneSearchDialogEt();
					} else {
						finish();
					}
				} else {
					finish();
				}
			}
		});
	}

	@Override
	public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
		switch (arg0.getId()) {
		case R.id.amusement_checkbox_area:
			if (amusementCheckboxArea.isChecked()) {
				pop1.showAsDropDown(amusementCheckboxArea);
				amusementCheckboxClassify.setChecked(false);
			}
			break;
		case R.id.amusement_checkbox_classify:
			if (amusementCheckboxClassify.isChecked()) {
				pop2.showAsDropDown(amusementCheckboxClassify);
				amusementCheckboxArea.setChecked(false);
			}
			break;
		case R.id.amusement_button_hot: // 热门
			FilterRequirement.juli = "";
			if (amusementButtonHot.isChecked()) {
				FilterRequirement.star = String.valueOf(2);
			} else {
				FilterRequirement.star = String.valueOf(1);
			}
			FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
			beginTransaction
					.replace(R.id.framelayout, AmusementInfoFragment.newInstance(AmusementActivity.this, 1, MContants.EMPTY_STRING));
			beginTransaction.commitAllowingStateLoss();
			break;
		case R.id.amusement_button_distance: // 距离
			FilterRequirement.star = "";
			if (amusementButtonDistance.isChecked()) {
				FilterRequirement.juli = String.valueOf(2);
			} else {
				FilterRequirement.juli = String.valueOf(1);
			}
			FragmentTransaction beginTransaction1 = getSupportFragmentManager().beginTransaction();
			beginTransaction1.replace(R.id.framelayout,
					AmusementInfoFragment.newInstance(AmusementActivity.this, 1, MContants.EMPTY_STRING));
			beginTransaction1.commitAllowingStateLoss();
			break;
		default:
			break;
		}
	}

	private final ContentObserver mGpsMonitor = new ContentObserver(null) {
		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			if (LoctionUtil.isOPen(AmusementActivity.this)) {
				dialog.dismiss();
				// 初始化数据

				if (flag_isfirst) {
					handler.sendEmptyMessage(3);
				}
			} else {
				// showShortToastMessage("GPS已经关闭!");
				handler.sendEmptyMessage(4);
			}
		}
	};

	@Override
	protected void onStart() {
		super.onStart();
	}

	class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			String initMessage = "初始化信息...";
			if (location == null)
				return;
			Logger.e("定位onReceiveLocation--initMessage:"+location.getLocType());
			FlyApplication.latitude = String.valueOf(location.getLatitude());
			FlyApplication.longitude = String.valueOf(location.getLongitude());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				// gps定位
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				// 网络定位
				FlyApplication.addr = location.getProvince(); // 省份
			}
			locationPd.setMessage(initMessage);
			// 1、定位成功之后关闭定位功能 -- 如果未成功就使用默认城市
			if (null != mLocationClient) {
				mLocationClient.stop();
			}
			handler.sendEmptyMessage(info_num);
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (null == poiLocation) {
				return;
			}
			FlyApplication.latitude = String.valueOf(poiLocation.getLatitude());
			FlyApplication.longitude = String.valueOf(poiLocation.getLongitude());
			if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
				FlyApplication.addr = poiLocation.getAddrStr();
			}
		}
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.title_but_right: // 显示搜索条的按钮
			// spw.showAsDropDown(titleRelativeLayout, LayoutParams.FILL_PARENT,
			// LayoutParams.FILL_PARENT);
			// 加上下面两行可以用back键关闭popupwindow，否则必须调用dismiss();
			// popupInputMethodWindow();
			if (searchLinearlayout.getVisibility() == View.GONE) {
				visibalSearchDialogEt();
			} else {
				goneSearchDialogEt();
			}
			break;
		case R.id.search_dialog_btn: // 点击搜索的按钮
			String string = searchDialogEt.getText().toString();
			if (StringUtil.isNullOrEmpty(string)) {
				showShortToastMessage(getString(R.string.search_cannot_empty));
			} else {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(searchDialogEt.getWindowToken(), 0);
				FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
				beginTransaction.replace(R.id.framelayout01, AmusementInfoFragment.newInstance(AmusementActivity.this, 2, string));
				beginTransaction.commitAllowingStateLoss();

			}
			break;
		case R.id.amusement_button_mapmodel:// 地图
			Intent intent = new Intent(this, AmuseMentMapActivity.class);
			FlyUtil.intentForward(this, intent);
			break;
		default:
			break;
		}
	}

	private void visibalSearchDialogEt() {
		searchLinearlayout.setVisibility(View.VISIBLE);
		searchLinearlayout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		Animation loadAnimation = AnimationUtils.loadAnimation(AmusementActivity.this, R.anim.push_bottom_in);
		loadAnimation.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation arg0) {
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				amusementLinearlayout.setVisibility(View.GONE);
			}
		});
		searchLinearlayout.setAnimation(loadAnimation);
		// editText.setFocusable(true);
		searchDialogEt.setFocusableInTouchMode(true);
		searchDialogEt.requestFocus();
		InputMethodManager inputManager = (InputMethodManager) searchDialogEt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		inputManager.showSoftInput(searchDialogEt, 0);
	}

	private void goneSearchDialogEt() {
		amusementLinearlayout.setVisibility(View.VISIBLE);
		searchLinearlayout.setVisibility(View.GONE);
		searchLinearlayout.setAnimation(AnimationUtils.loadAnimation(AmusementActivity.this, R.anim.push_bottom_out));
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(searchDialogEt.getWindowToken(), 0);
	}

	private Handler handler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			// Auto-generated method stub
			super.dispatchMessage(msg);
			switch (msg.what) {
			case 1:
				String initInfo = getString(R.string.initInfo);
				asynctask = new ItktAsyncTaskWithDialog<Void, Void, AreaListVo>(initInfo, false, true) {
					@Override
					public AreaListVo before(Void... params) throws Exception {

						return RemoteImpl.getInstance().getAreaListVo(FilterRequirement.TYPE, null);
					}

					@Override
					public void after(AreaListVo result) {
						if (result != null) {
							if (locationPd != null) {
								locationPd.dismiss();
							}
							if (result.getCode() == Code.CODE_SUCCESS) {
								if (result.getQuyulist() != null) {
									pop1 = new PopupWindow(AmusementActivity.this);
									// 适配区域信息
									pop2 = new PopupWindow(AmusementActivity.this);
									screenlistview = new ScreenListView(AmusementActivity.this, result, 1, handler);
									screenlistview1 = new ScreenListView(AmusementActivity.this, result, 2, handler);
									pop1.setContentView(screenlistview.loadView());
									pop2.setContentView(screenlistview1.loadView());
									// pop1和pop2数据加载完之后再让点击
									showCheckboxclick();
									setUpPop(pop1);
									setUpPop(pop2);
									// 2、定位成功之后根据定位到的城市，去获取所对应的娱乐信息
									beginTransaction.replace(R.id.framelayout,
											AmusementInfoFragment.newInstance(getApplicationContext(), 1, MContants.EMPTY_STRING));
									beginTransaction.commitAllowingStateLoss();
								}
							}
						}
					}

					// onCancelled方法用于在取消执行中的任务时更改UI
					@Override
					protected void onCancelled() {
					}

					private void showCheckboxclick() {
						amusementCheckboxArea.setClickable(true);
						amusementCheckboxClassify.setClickable(true);
						amusementButtonDistance.setClickable(true);
						amusementButtonHot.setClickable(true);
						amusementButtonMapModel.setClickable(true);
						templateButtonRight.setClickable(true);
					}

					@Override
					public void exception() {
						// Auto-generated method stub
					}
				};
				asynctask.execute();
				break;
			case ScreenListView.POPNUM1:
				pop2.dismiss();
				FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
				beginTransaction.replace(R.id.framelayout,
						AmusementInfoFragment.newInstance(getApplicationContext(), 1, MContants.EMPTY_STRING));
				beginTransaction.commitAllowingStateLoss();
				break;
			case ScreenListView.POPNUM2:
				pop1.dismiss();
				FragmentTransaction beginTransaction1 = getSupportFragmentManager().beginTransaction();
				beginTransaction1.replace(R.id.framelayout,
						AmusementInfoFragment.newInstance(getApplicationContext(), 1, MContants.EMPTY_STRING));
				beginTransaction1.commitAllowingStateLoss();
				break;
			case 3:
				showShortToastMessage(getString(R.string.gps_opened));
				showLocaltion(true);
				break;
			case 4:
				showShortToastMessage(getString(R.string.gps_closed));
				break;
			case ScreenListView.POPNUMALL:
				pop2.dismiss();
				pop1.dismiss();
				FragmentTransaction beginTransaction2 = getSupportFragmentManager().beginTransaction();
				beginTransaction2.replace(R.id.framelayout,
						AmusementInfoFragment.newInstance(getApplicationContext(), 1, MContants.EMPTY_STRING));
				beginTransaction2.commitAllowingStateLoss();
				break;
			}
		}

	};
	private FragmentTransaction beginTransaction;

	/**
	 * 
	 * @author czz
	 * @createdate 2014-7-2 上午10:07:30
	 * @Description: (设置popwindow)
	 * @param pop
	 * 
	 */
	private void setUpPop(PopupWindow pop) {
		pop.setWidth(popwidth);
		pop.setHeight(popheight);
		// 实例化一个ColorDrawable颜色为半透明
		ColorDrawable dw = new ColorDrawable(R.color.half_transparent);
		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(dw);
		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);
		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);
		pop.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				amusementCheckboxArea.setChecked(false);
				amusementCheckboxClassify.setChecked(false);
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		FilterRequirement.clearCondition();
		if (null != mGpsMonitor) {
			// 注销 gps监听广播
			getContentResolver().unregisterContentObserver(mGpsMonitor);
		}
		if (null != asynctask && AsyncTask.Status.RUNNING == asynctask.getStatus()) {
			asynctask.cancel(true);// 如果Task还在运行，则先取消它
			asynctask = null;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (null != searchLinearlayout) {
				if (searchLinearlayout.getVisibility() == View.VISIBLE) {
					goneSearchDialogEt();
					return true;
				}
			}
			return super.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}

	/*
	 * private void popupInputMethodWindow() { handler.postDelayed(new
	 * Runnable() { private InputMethodManager imm;
	 * 
	 * @Override public void run() { imm = (InputMethodManager)
	 * searchDialogEt.getContext()
	 * .getSystemService(Service.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0,
	 * InputMethodManager.HIDE_NOT_ALWAYS); } }, 0); }
	 */
}
